//
//  MyContactsViewController.m
//  绿地管理系统
//
//  Created by rimi on 16/1/18.
//  Copyright © 2016年 hexs. All rights reserved.
//

#import "MyContactsViewController.h"
#import "LoginViewController.h"
#import "XSViewController.h"
#import "MyContactsViewModel.h"
#import "NetworkingManager+Public.h"
#import "NetworkingManager+People.h"
#import "MyContactsCell.h"
#import "qqViewController.h"



@interface MyContactsViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) MyContactsViewModel *viewModel;
@property (nonatomic, strong) UITableView *myPeopleListTableView;
@property (nonatomic, strong) NSMutableArray *buttonStates;
@property (nonatomic, strong) UISegmentedControl *segmented;
@property (nonatomic, strong) UIImageView *separateView;


// KVO
- (void)registerObserver;
- (void)unregisterObserver;
// 注册通知
- (void)registerNotification;

- (void)initializeAppearance;

@end

@implementation MyContactsViewController
- (void)dealloc
{
    [self unregisterObserver];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
//    self.view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"4cee017297a112291522c86b2a1f9ebb_r.jpg"].CGImage);

    
    [self registerObserver];
    [self registerNotification];
    [self initializeAppearance];
    
    // 判断是否自动登录
    BOOL isAutoLogin = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AutoLogin"] boolValue];
    if (isAutoLogin) {
        // 调用登录接口，登录成功后再调用首页数据的接口
        // 需要上次登录成功的用户名和密码
        // 用UD来拿
        //登录接口成功后：
        NSString * username = [[NSUserDefaults standardUserDefaults] objectForKey:@"Username"];
        NSString * password = [[NSUserDefaults standardUserDefaults] objectForKey:@"Password"];
        [NetWorkingManager loginWithUsername:username password:password successHandler:^(id responseObj) {
            
            [self updateDataSource];
            
        } failureHandler:^(NSError *error) {
            // 网络请求失败
        }];
    }
    
}
- (void)viewDidAppear:(BOOL)animated
{
    BOOL isAutoLogin = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AutoLogin"] boolValue];
    if (!isAutoLogin) {
        LoginViewController * loginVC = [[LoginViewController alloc] init];
        [self presentViewController:loginVC animated:NO completion:nil];
    }
}

- (void)initializeAppearance
{
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.frame = CGRectMake(0, 0, 50, 50);
//    addButton.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"新增人脉_03@2x" ]];
    [addButton setImage:[UIImage imageNamed:@"新增人脉_03@2x"] forState:UIControlStateNormal];
    UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    searchButton.frame = CGRectMake(0, 0, 50, 50);
    [searchButton setImage:[UIImage imageNamed:@"搜索_03"] forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(onSearchButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *seatchItem = [[UIBarButtonItem alloc] initWithCustomView:searchButton];
    
    
    self.navigationItem.leftBarButtonItem = seatchItem;
    self.navigationItem.rightBarButtonItem = addItem;
    
    [self.view addSubview:self.myPeopleListTableView];
    [self.view addSubview:self.segmented];
    [self.view addSubview:self.separateView];
}

#pragma mark -- private Methods
- (void)registerObserver
{
    [self.viewModel addObserver:self forKeyPath:[self.viewModel observingKeyPath] options:NSKeyValueObservingOptionNew context:nil];
}
- (void)unregisterObserver
{
    [self.viewModel removeObserver:self forKeyPath:[self.viewModel observingKeyPath]];
}
// 注册通知，一旦有名字为LoginSuccess的通知发出，就会响应respondsToNotification方法
- (void)registerNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(respondsToNotification) name:@"LoginSuccess" object:nil];
}
// 响应通知，通知一来，就请求首页数据
- (void)respondsToNotification
{
    [self updateDataSource];
}
// 请求首页数据
- (void)updateDataSource
{
    [self.viewModel getData];
}


- (void)onSearchButton:(UIButton *)sender
{
    XSViewController *drawerVC = (XSViewController *)self.parentViewController.parentViewController.parentViewController;
//    XSViewController *drawerVC = [[XSViewController alloc] init];
    [drawerVC openLeftDrawer];
}

- (void)segmentedValueChanged:(UISegmentedControl *)sender
{
    
}

#pragma KVO callback
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([self.viewModel isSuccess]) {
        [self.myPeopleListTableView reloadData];
    } else {
    
    }
}

#pragma mark --<UITableViewDataSource, UITableViewDelegate>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.viewModel numberOfRowsInSection:section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyContactsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdf" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.name = [self.viewModel cellNameForRowAtIndexPath:indexPath];
//    NSLog(@"---------------------------------%@",cell.name);
    cell.photoUrl = [self.viewModel cellPhotoUrlForRowAtIndexPath:indexPath];
    cell.gender = [self.viewModel cellGenderForRowAtIndexPath:indexPath];
    cell.relationList = [self.viewModel cellRelationListForRowAtIndexPath:indexPath];
    
    cell.cellButtonAction = ^(MyContactsCell *cell, UIButton *button) {
        [self.buttonStates replaceObjectAtIndex:indexPath.row withObject:@(button.selected)];
        [tableView reloadData];
    };
    
    return cell;
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    qqViewController *qq = [qqViewController new];
//    [self.navigationController pushViewController:qq animated:YES];
//}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 通过indexPath获取这个cell将要显示的数据（字典）
    // 通过这个数据（字典）计算出这个cell应该显示的高度
    
    // 如何判断是否是展开
    // 先要拿到cell里面那个button
    // 先要拿到这个cell
    
    return [self.viewModel heightForCellAtIndexPath:indexPath isExpand:[self.buttonStates[indexPath.row] boolValue]];
}


#pragma mark -- getter
- (MyContactsViewModel *)viewModel
{
    if (_viewModel == nil) {
        _viewModel = [[MyContactsViewModel alloc] init];
    }
    return _viewModel;
}

- (UITableView *)myPeopleListTableView
{
    if (_myPeopleListTableView == nil) {
        _myPeopleListTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 60, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) style:UITableViewStylePlain];
        _myPeopleListTableView.dataSource = self;
        _myPeopleListTableView.delegate = self;
        [_myPeopleListTableView registerClass:[MyContactsCell class] forCellReuseIdentifier:@"cellIdf"];
        _myPeopleListTableView.tableFooterView = [[UIView alloc] init];
        _myPeopleListTableView.separatorStyle = UITableViewCellSelectionStyleNone;
        _myPeopleListTableView.backgroundColor = [UIColor clearColor];
    }
    return _myPeopleListTableView;
}

- (NSMutableArray *)buttonStates
{
    if (_buttonStates == nil) {
        _buttonStates = [NSMutableArray array];
        for (int i = 0; i < [self.viewModel numberOfRowsInSection:0]; i++) {
            [_buttonStates addObject:@(NO)];
        }
    }
    return _buttonStates;
}
- (UISegmentedControl *)segmented
{
    if (_segmented == nil) {
        _segmented = [[UISegmentedControl alloc] initWithItems:@[@"我的人脉", @"时间轴"]];
//        [_segmented setImage:[UIImage imageNamed:@"时间轴未点击_03"] forSegmentAtIndex:0];
//        [_segmented setImage:[UIImage imageNamed:@"我的人脉点击11_03"] forSegmentAtIndex:1];
//        [_segmented
        _segmented.frame = CGRectMake(100, 70, 175, 20);
//        _segmented.center = CGPointMake(self.view.center.x, 90);
        _segmented.selectedSegmentIndex = 2;
        // NSLog(@"%ld",(long)segmented.selectedSegmentIndex);
        // segmented.momentary = YES;
        [_segmented addTarget:self action:@selector(segmentedValueChanged:) forControlEvents:UIControlEventValueChanged];

    }
    return _segmented;
}

- (UIImageView *)separateView
{
    if (_separateView == nil) {
        _separateView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 90, CGRectGetWidth(self.view.bounds), 15)];
        _separateView.image = [UIImage imageNamed:@"分割线_03"];
    }
    return _separateView;
}
@end











